<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="所属分类" prop="type">
        <el-select v-model="queryParams.type" clearable placeholder="请选择所属分类">
          <el-option
            v-for="type in typeOptions"
            :key="type.dictValue"
            :value="type.dictValue"
            :label="type.dictLabel"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model.trim="queryParams.title" placeholder="请填写标题" clearable></el-input>
      </el-form-item>
      <el-form-item label="关键字" prop="keywords">
        <el-input v-model.trim="queryParams.keywords" clearable placeholder="请填写关键字"></el-input>
      </el-form-item>
      <!--      <el-form-item label="内容" prop="content">-->
      <!--        <el-input v-model.trim="queryParams.content" clearable placeholder="请填写内容"></el-input>-->
      <!--      </el-form-item>-->
      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
    </el-form>

    <el-table v-loading="loading" :data="knowledgelist" border>
      <el-table-column label="序号" align="center" type="index" width="50" fixed></el-table-column>
      <el-table-column label="所属分类" prop="type" :formatter="formatType" header-align="center" align="center" width="120" />
      <el-table-column label="标题" prop="title" :show-overflow-tooltip="true" header-align="center" />
      <el-table-column label="关键字" prop="keywords" :show-overflow-tooltip="true" header-align="center" />
      <!--      <el-table-column label="内容" prop="content" :show-overflow-tooltip="true" header-align="center">-->
      <!--        <template slot-scope="scope">-->
      <!--          <div v-html="scope.row.content"></div>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="创建人" prop="createBy" :show-overflow-tooltip="true" width="120" header-align="center" align="center" />
      <el-table-column label="创建时间" prop="createTime" :show-overflow-tooltip="true" width="180" header-align="center" align="center" />
      <el-table-column label="操作" align="center" header-align="center" class-name="small-padding" width="230">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleViewContent(scope.row)"
          >查看内容</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listCustom } from '@/api/custom/custom'
import {
  deleteAttachFile,
  deleteKnowledgeById,
  insertKnowledge, selectAllKnowledgeList,
  selectKnowledgeById,
  selectKnowledgeList, selectPublicKnowledgeList,
  updateKnowledge, uploadAttachFile, uploadFile
} from '@/api/knowledge/knowledge'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import "@wangeditor/editor/dist/css/style.css"
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'
import { mapGetters } from 'vuex'

export default {
  name: 'Query',
  components: {
    Editor,
    Toolbar
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 客户列表
      customList: [],
      // 弹出层标题
      title: '',
      // 是否显示新增/编辑弹窗
      showDialog: false,
      // 是否显示内容弹窗
      showContentDialog: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: '',
        title: '',
        keywords: '',
        content: '',
        status: ''
      },
      // 列表数据
      knowledgelist: [],
      // 状态选项
      statusOptions: [{
        label: '正常',
        value: '1'
      },{
        label: '禁用',
        value: '0'
      }
      ],
      // 所属分类选项
      typeOptions: [],
      // 表单
      knowledgeForm: {
        id: '',
        type: '',
        title: '',
        keywords: '',
        content: '',
        attachList: []
      },
      // 附件列表
      attachFileList: [],
      // 是否全屏
      fullscreen: false,
      // 表单数据校验
      knowledgeFormRules: {
        type: [
          { required: true, message: "所属分类必须选择", trigger: ['blur', 'change'] }
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: ['blur', 'change'] }
        ],
        keywords: [
          { required: true, message: "关键字不能为空", trigger: ['blur', 'change'] }
        ]
      },
      // 富文本编辑器配置信息
      wangEditor: {
        editor: null,
        html: '',
        toolbarConfig: {
          excludeKeys: [
            'insertImage',
            'insertVideo',
            'fullScreen'
          ]
        },
        editorConfig: {
          placeholder: '请输入内容...',
          MENU_CONF: {
            uploadImage: {
              server: process.env.VUE_APP_BASE_API + '/knowledge/uploadFile',
              fieldName: 'file',
              maxFileSize: 10 * 1024 * 1024,
              maxNumberOfFiles: 10,
              headers: {
                Accept: 'application/json;charset=UTF-8',
                Authorization: getToken()
              },
              withCredentials: true,
              timeout: 10 * 1000,
              onBeforeUpload(files){
                Message({
                  message: '图片正在上传中,请耐心等待',
                  duration: 0,
                  customClass: 'uploadTip',
                  iconClass: 'el-icon-loading',
                  showClose: true
                });
                return files;
              },
              onDelete(file){
                console.log('dsdsdsdsdsds')
              },
              // 自定义插入图片
              customInsert(res, insertFn) {
                console.log('res = ' + JSON.stringify(res))
                // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
                // 先关闭等待的Message
                Message.closeAll();
                if (res.code === 200) {
                  Message.success({
                    message: `${res.data.originalName} 上传成功`
                  });
                } else {
                  Message.error({
                    message: `${res.data.originalName} 上传失败，请重新尝试`
                  });
                }
                insertFn(res.data.link, res.data.name, res.data.link);
              },
              // 单个文件上传成功之后
              onSuccess(file, res) {
                console.log(`${file.name} 上传成功`, res);
              },

              // 单个文件上传失败
              onFailed(file, res) {
                console.log(`${file.name} 上传失败`, res);
              },

              // 上传进度的回调函数
              onProgress(progress) {
                console.log('progress', progress);
                // progress 是 0-100 的数字
              },

              // 上传错误，或者触发 timeout 超时
              onError(file, err, res) {
                console.log(`${file.name} 上传出错`, err, res);
                Message.closeAll();
                Message.error({
                  message: `${file.name} 上传出错`
                });
              }
            },
            uploadVideo: {
              server: process.env.VUE_APP_BASE_API + '/knowledge/uploadFile',
              fieldName: 'file',
              maxFileSize: 50 * 1024 * 1024,
              maxNumberOfFiles: 3,
              headers: {
                Accept: 'application/json;charset=UTF-8',
                Authorization: getToken()
              },
              withCredentials: true,
              timeout: 1000 * 1000,
              onBeforeUpload(files){
                Message({
                  message: '视频正在上传中,请耐心等待',
                  duration: 0,
                  customClass: 'uploadTip',
                  iconClass: 'el-icon-loading',
                  showClose: true
                });
                return files;
              },
              // 自定义插入视频
              customInsert(res, insertFn) {
                console.log('res = ' + JSON.stringify(res))
                // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
                // 先关闭等待的Message
                Message.closeAll();
                if (res.code === 200) {
                  Message.success({
                    message: `${res.data.originalName} 上传成功`
                  });
                } else {
                  Message.error({
                    message: `${res.data.originalName} 上传失败，请重新尝试`
                  });
                }
                insertFn(res.data.link, res.data.name, res.data.link);
              },
              // 单个文件上传成功之后
              onSuccess(file, res) {
                console.log(`${file.name} 上传成功`, res);
              },

              // 单个文件上传失败
              onFailed(file, res) {
                console.log(`${file.name} 上传失败`, res);
              },

              // 上传进度的回调函数
              onProgress(progress) {
                console.log('progress', progress);
                // progress 是 0-100 的数字
              },

              // 上传错误，或者触发 timeout 超时
              onError(file, err, res) {
                console.log(`${file.name} 上传出错`, err, res);
                Message.closeAll();
                Message.error({
                  message: `${file.name} 上传出错`
                });
              }
            }
          }
        },
        mode: 'default'
      }
    }
  },
  computed: {
    ...mapGetters([
      'userid',
      'name',
      'roles'
    ])
  },
  created() {
    this.getDicts("knowledge_type").then(response => {
      this.typeOptions = response.data;
    })
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true;
      selectPublicKnowledgeList(this.queryParams).then(response => {
          this.knowledgelist = response.rows
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    handleQuery() {
      this.getList()
    },
    formatType(row) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },

    onEditorCreated(editor){
      this.wangEditor.editor = Object.seal(editor)
    },
    setEditorReadOnly(editor){
      this.wangEditor.editor = Object.seal(editor)
      this.wangEditor.editor.disable()
    },

    handleViewContent(row) {
      window.open('/zsk/knowledge/view?id=' + row.id, '_blank')
    },
  },
  beforeDestroy() {
    const editor = this.wangEditor.editor
    if(editor == null) return
    editor.destroy()
  }
}
</script>

<style scoped lang="scss">
.full-screen {
  cursor: pointer;
  font-size: 22px;
  display: block;
  color: #666666;
  width: 22px;
  height: 22px;
  margin-right: 10px;
}
.full-screen.fd {
  background-image: url("../../assets/image/fd.png");
  background-size: 100% 100%;
}
.full-screen.sx {
  background-image: url("../../assets/image/sx.png");
  background-size: 100% 100%;
}
</style>
